﻿using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using JiaBao.Services;
using JiaBao.Services.AuctionService;
using JiaBao.Services.CustomerService;
using JiaBao.Services.JtdjService;
using JiaBao.Services.LogService;
using JiaBao.Services.SalerService;
using JiaBao.WPF.Dialog;

namespace JiaBao.WPF.Customer
{


    /// <summary>
    /// uc_Customer_Saler.xaml 的交互逻辑
    /// </summary>
    public partial class p_Customer_Saler : Page
    {
        /// <summary>
        /// 当前页面线程
        /// </summary>
        Dispatcher Mainthread = Dispatcher.CurrentDispatcher;

        #region Fileds

        private CustomerType _customerType;
        /// <summary>
        /// 页面类型
        /// </summary>
        public CustomerType CustomerType
        {
            get => _customerType;

            set
            {
                _customerType = value;
                DialgHost.Identifier = _customerType.ToString() + "_Dialg";
            }
        }

        /// <summary>
        /// 客户
        /// </summary>
        public ICustomerService _customerService { get; }

        /// <summary>
        /// 拍卖会
        /// </summary>
        private readonly IAuctionService _auctionService;

        /// <summary>
        /// 卖家
        /// </summary>
        private readonly ISalerService _salerService;

        /// <summary>
        /// 买家
        /// </summary>
        private readonly IJtdjService _jtdjService;

        #endregion

        #region Ctor

        public p_Customer_Saler(ICustomerService customerService, IAuctionService auctionService, ISalerService salerService, IJtdjService jtdjService)
        {
            _customerService = customerService;
            _auctionService = auctionService;
            _salerService = salerService;
            _jtdjService = jtdjService;
            InitializeComponent();

            try
            {
                //拍卖会
                DataTable dt = _auctionService.GetAll();
                cmb_Auction.ItemsSource = dt.DefaultView;
                cmb_Auction.DisplayMemberPath = "拍卖会名称";
                cmb_Auction.SelectedValuePath = "拍卖会ID";

            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }



        }

        #endregion

        #region 拍卖会筛选

        private void Cmb_Auction_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetCustomerToDataGrid();
        }
        private void Ck_Only_Checked(object sender, RoutedEventArgs e)
        {
            GetCustomerToDataGrid();
        }
        private void Ck_Only_Unchecked(object sender, RoutedEventArgs e)
        {
            GetCustomerToDataGrid();
        }

        /// <summary>
        /// 获取客户资料
        /// </summary>
        /// <param name="byId">是否有拍卖会id</param>
        private void GetCustomerToDataGrid(bool byId = true)
        {

            try
            {
                DataTable dt;
                switch (CustomerType)
                {
                    case CustomerType.Jtdj:
                        if (!byId)
                        {
                            cmb_Auction.SelectedIndex = -1;
                            dt = _jtdjService.GetAllOnlyNo();
                        }
                        else
                        {
                            if (null == cmb_Auction.SelectedItem) return;
                            dt = true == ck_Only.IsChecked ?
                                  _jtdjService.GetByAucIdAndOnlyNo((int)cmb_Auction.SelectedValue) :
                                  _jtdjService.GetByAucId((int)cmb_Auction.SelectedValue);
                        }
                        break;

                    case CustomerType.Saler:
                        if (!byId)
                        {
                            cmb_Auction.SelectedIndex = -1;
                            dt = _salerService.GetAllOnlyNo();
                        }
                        else
                        {
                            if (null == cmb_Auction.SelectedItem) return;
                            dt = true == ck_Only.IsChecked ?
                                  _salerService.GetByAucIdAndOnlyNo((int)cmb_Auction.SelectedValue) :
                                  _salerService.GetByAucId((int)cmb_Auction.SelectedValue);
                        }
                        break;

                    default:
                        return;

                }
                dg_Main.ItemsSource = dt.DefaultView;
                dg_Main.Columns[0].IsReadOnly = true;

                for (int i = dg_Main.Column("客户标识Z").DisplayIndex; i < dg_Main.Columns.Count; i++)
                {
                    dg_Main.Columns[i].Visibility = Visibility.Hidden;
                    dg_Main.Columns[i].IsReadOnly = true;
                }

            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }


        }

        /// <summary>
        /// 查看所有未整理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_AllOnly_Click(object sender, RoutedEventArgs e)
        {
            GetCustomerToDataGrid(false);
        }


        #endregion

        /// <summary>
        /// 及时更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg_Main_CellEditEnd(object sender, DataGridCellEditEndingEventArgs e)
        {
            try
            {
                var colName = e.Column.Header;
                var newValue = (e.EditingElement as TextBox).Text;

                string sql;
                DataRowView selectItem = dg_Main.Items[e.Row.GetIndex()] as DataRowView;

                switch (CustomerType)
                {
                    case CustomerType.Jtdj:
                        var aucid = selectItem["拍卖会id"];
                        var jtph = selectItem["竞投牌号"];
                        sql = string.Format("update jtdjall set {0} = @value where 拍卖会id = @aucid and 竞投牌号 = @jtp", colName);
                        _jtdjService.ExecuteNonQuery(sql, new SqlParameter("value", newValue), new SqlParameter("aucid", aucid), new SqlParameter("jtp", jtph));
                        break;

                    case CustomerType.Saler:
                        var id = selectItem["拍卖会id"];
                        var htbh = selectItem["合同编号"];
                        sql = string.Format("update salerall set {0} = @value where 拍卖会id = @aucid and 合同编号 = @htbh", colName);
                        _salerService.ExecuteNonQuery(sql, new SqlParameter("value", newValue), new SqlParameter("aucid", id), new SqlParameter("htbh", htbh));
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 整理本届
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ZL_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (null == cmb_Auction.SelectedItem) return;

                var loadingDialog = new LoadingDialog();
                var result = await DialogHost.Show(loadingDialog, CustomerType.ToString() + "_Dialg", delegate (object sender1, DialogOpenedEventArgs args)
                {


                    ThreadStart start = delegate ()
                    {

                        Thread.Sleep(100);
                        Mainthread.BeginInvoke((Action)delegate ()// 异步更新界面
                        {

                            int r = 0;
                            switch (CustomerType)
                            {
                                case CustomerType.Jtdj:
                                    r = _jtdjService.UpdateByAucId((int)cmb_Auction.SelectedValue);
                                    break;

                                case CustomerType.Saler:
                                    r = _salerService.UpdateByAucId((int)cmb_Auction.SelectedValue);
                                    break;

                                default:
                                    break;
                            }
                            var c = _customerService.Update();

                            GetCustomerToDataGrid();

                            args.Session.Close(false);
                        });

                    };

                    new Thread(start).Start(); // 启动线程

                });

            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 整理全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ZLAll_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show("确认全部整理,这需要时间较长,可能出现超时", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) return;
                var loadingDialog = new LoadingDialog();
                var result = await DialogHost.Show(loadingDialog, CustomerType.ToString() + "_Dialg", delegate (object sender1, DialogOpenedEventArgs args)
                { 
                    ThreadStart start = delegate ()
                    { 
                        Thread.Sleep(100);
                        Mainthread.BeginInvoke((Action)delegate ()// 异步更新界面
                        {
                            int r = 0;
                            switch (CustomerType)
                            {
                                case CustomerType.Jtdj:
                                    r = _jtdjService.UpdateByAucId(-100);
                                    break;

                                case CustomerType.Saler:
                                    r = _salerService.UpdateByAucId(-100);
                                    break;

                                default:
                                    break;
                            }
                            GetCustomerToDataGrid(false);

                            args.Session.Close(false);
                        });

                    };

                    new Thread(start).Start(); // 启动线程

                });
            }
            catch (Exception ex)
            {
                Log.SaveLog(ex);
                MessageBox.Show(ex.Message);
            }
        }


    }
}
